import { useState, useCallback, useMemo } from 'react';

// 流量单位转换函数 - 统一转换为 KB 进行排序
const convertTrafficToKB = (value: any): number => {
  if (value == null || value === '') return 0;
  
  const str = String(value).toLowerCase().trim();
  
  // 如果是纯数字，假设是 KB
  if (/^\d+(\.\d+)?$/.test(str)) {
    return Number(str);
  }
  
  // 提取数字和单位 - 支持更灵活的单位格式
  const match = str.match(/^(\d+(?:\.\d+)?)\s*(kb|mb|gb|tb|b)?$/);
  if (!match) {
    // 如果正则匹配失败，尝试直接解析数字
    const numMatch = str.match(/^(\d+(?:\.\d+)?)/);
    if (numMatch) {
      return Number(numMatch[1]); // 假设是 KB
    }
    return 0;
  }
  
  const num = Number(match[1]);
  const unit = match[2] || 'kb';
  
  // 统一转换为 KB
  switch (unit) {
    case 'b':
      return num / 1024; // 字节转 KB
    case 'kb':
      return num; // 已经是 KB
    case 'mb':
      return num * 1024; // MB 转 KB
    case 'gb':
      return num * 1024 * 1024; // GB 转 KB
    case 'tb':
      return num * 1024 * 1024 * 1024; // TB 转 KB
    default:
      return num; // 默认当作 KB
  }
};

export type SortOrder = 'asc' | 'desc' | null;

export interface SortState {
  sortKey: string | null;
  sortOrder: SortOrder;
}

export interface UseTableSortOptions<T> {
  initialSortKey?: string;
  initialSortOrder?: SortOrder;
  onSortChange?: (sortKey: string, sortOrder: SortOrder) => void;
}

export function useTableSort<T = any>(options: UseTableSortOptions<T> = {}) {
  const {
    initialSortKey = null,
    initialSortOrder = null,
    onSortChange,
  } = options;

  const [sortState, setSortState] = useState<SortState>({
    sortKey: initialSortKey,
    sortOrder: initialSortOrder,
  });

  const handleSort = useCallback((sortKey: string, sortOrder: SortOrder) => {
    setSortState({ sortKey, sortOrder });
    onSortChange?.(sortKey, sortOrder);
  }, [onSortChange]);

  const clearSort = useCallback(() => {
    setSortState({ sortKey: null, sortOrder: null });
    onSortChange?.('', null);
  }, [onSortChange]);

  const sortedData = useMemo(() => {
    return (data: T[], sortKey: string | null, sortOrder: SortOrder) => {
      if (!sortKey || !sortOrder || !data.length) {
        return data;
      }

      return [...data].sort((a: any, b: any) => {
        const aValue = a[sortKey];
        const bValue = b[sortKey];

        // 处理 null 和 undefined 值
        if (aValue == null && bValue == null) return 0;
        if (aValue == null) return 1;
        if (bValue == null) return -1;

        // 处理流量数据（包含单位的字符串）
        if (sortKey === 'traff_count_real' || sortKey === 'traff_count' || 
            sortKey === 'up_bytes' || sortKey === 'down_bytes') {
          const aKB = convertTrafficToKB(aValue);
          const bKB = convertTrafficToKB(bValue);
          
          return sortOrder === 'asc' ? aKB - bKB : bKB - aKB;
        }

        // 处理数字类型（包括字符串数字）
        const aNum = Number(aValue);
        const bNum = Number(bValue);
        if (!isNaN(aNum) && !isNaN(bNum)) {
          // 修复排序方向：ChevronUpIcon 应该是升序（小到大），ChevronDownIcon 应该是降序（大到小）
          return sortOrder === 'asc' ? aNum - bNum : bNum - aNum;
        }

        // 处理字符串类型
        if (typeof aValue === 'string' && typeof bValue === 'string') {
          const comparison = aValue.localeCompare(bValue);
          return sortOrder === 'asc' ? comparison : -comparison;
        }

        // 处理日期类型
        if (aValue instanceof Date && bValue instanceof Date) {
          const comparison = aValue.getTime() - bValue.getTime();
          return sortOrder === 'asc' ? comparison : -comparison;
        }

        // 处理时间戳（数字）
        if (typeof aValue === 'number' && aValue > 1000000000 && 
            typeof bValue === 'number' && bValue > 1000000000) {
          return sortOrder === 'asc' ? aValue - bValue : bValue - aValue;
        }

        // 默认字符串比较
        const aStr = String(aValue);
        const bStr = String(bValue);
        const comparison = aStr.localeCompare(bStr);
        return sortOrder === 'asc' ? comparison : -comparison;
      });
    };
  }, []);

  return {
    sortState,
    handleSort,
    clearSort,
    sortedData,
    isSorted: (key: string) => sortState.sortKey === key,
    getSortOrder: (key: string) => sortState.sortKey === key ? sortState.sortOrder : null,
  };
}

export default useTableSort;
